package com.fengye.cluster.impl;

import com.fengye.cluster.ClusterStrategy;
import com.fengye.model.ProviderService;
import com.google.common.collect.Lists;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author fengye
 * @Date 2023/2/15 12:51
 **/
public class WeightRandomClusterStrategyImpl implements ClusterStrategy {
    @Override
    public ProviderService select(List<ProviderService> providerServiceList) {
        List<ProviderService> providerServices = Lists.newLinkedList();
        for (ProviderService provider : providerServices) {
            int weight = provider.getWeight();
            for (int i=0;i < weight;i++) {
                providerServices.add(provider.clone());
            }
        }
        int maxLen = providerServices.size();
        int index = ThreadLocalRandom.current().nextInt(0, maxLen-1);
        return providerServices.get(index);
    }
}
